package net;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//模拟客户端
public class UdpEchoClient {
    private String serverIP;
    private int serverPort;
    private DatagramSocket socket;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        //new一个socket对象,通过socket对象内提高的接口来发送请求和接受响应
        //注意我们这里new的socket并没有指定端口号, 因为这是是客户端, 客户端的端口号不能固定 而服务器的端口号是固定的
        this.socket = new DatagramSocket();//这里得端口号由操作系统自行分配
    }

    public void start() throws IOException {
        System.out.println("启动客户端");
        while (true) {
            //1.获取用户输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("输入你要发送的请求数据");
            if (!scanner.hasNext()) {
                break;
            }
            String request = scanner.next();
            //2.发送请求给服务器,需要构造DatagramPacket对象
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length, InetAddress.getByName(serverIP), serverPort);
            //3.发送请求
            socket.send(requestPacket);
            //4.接受响应,并解析响应数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[4024], 4024);
            //同理这里如果响应没回来, 这儿会阻塞
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println("服务器响应:" + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
